let prefix = "/jzweb/trackDraw";
let isDrawing = null;
let flag = false; // 标记是否正在进行抽签
let animationId;
let paging = 1;

$(function() {
    document.title = '竞赛管理平台'; // 动态设置网页标题
    $('link[rel="shortcut icon"]').attr('href', `${'../../static/favicon.ico'}`)
    if(window.location.href.split('?')[1]) {
        $('.openPages').show()
    }else {
        $('.openPages').hide()
    }

    $.ajax({
        cache : true,
        type : "post",
        url : "/jzweb/stuSignUpCom/cbatchList",
        data:{
            types: 3,
        },
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {

            if (data.code == 0) {
                let str = '';
                data.data?.map(function (v,k){
                    // if ( k == 0 ) str += `<option value="">请选择</option>`
                    str += `<option value="${v.id}">${v.name}</option>`
                })
                $("#cbatchName").html(str);
                load();
            } else {
                parent.layer.alert(data.msg)
            }
        }
    });

    $("#cbatchName").change(() => {
        reLoad()
    })

});

function columnsCreate() {
    return [
        { field: 'recordNumber', title: '序号', class: 'index-cell' },     // 保持原字段，增加类名，动画时覆盖显示
        { field: 'unitName', title: '学校名称' },
        {
            field: 'name1',
            title: '参赛选手',
            formatter: function(value, row) {
                // ✅ 拼接 name1 ~ name4 并过滤空值
                const pool = [row.name1, row.name2, row.name3, row.name4]
                    .filter(n => n && String(n).trim() !== '');
                return pool.join('，') || '-';
            }
        },
        { field: 'sort1', title: '理论选手', class: 'theory-cell',
            formatter: function(value, row) {
                // ✅ 拼接 name1 ~ name4 并过滤空值
                const pool = [row.checkName1, row.checkName2]
                    .filter(n => n && String(n).trim() !== '');
                return pool.join('，') || '-';
            }
        } // 动画时从 name1~name4 随机滚动
    ];
}
function load() {
    $('#exampleTable').bootstrapTable({
        method: 'get',
        url: '/jzweb/trackDraw/exportDrawList',
        iconSize: 'outline',
        toolbar: '#exampleToolbar',
        theadClasses: "thead-dark",
        striped: true,
        dataType: "json",
        pagination: true,
        singleSelect: false,
        pageSize: 999999,
        pageNumber: 1,
        showColumns: false,
        sidePagination: "server",
        queryParamsType: "",
        paginationDetail: false,
        pageList: [15, 25, 50, 100],
        queryParams: function(params) {
            paging = params.pageNumber;
            return {
                cbatchId: $('#cbatchName').val()
            };
        },
        responseHandler: function(res) {
            if (res.code !== '0') {
                layer.msg(res.msg);
                return false;
            }
            let { data } = res;
            isDrawing = data[0];
            return {
                "rows": data,
                "total": res.data.total,
            };
        },
        columns: columnsCreate()
    });
}

function reLoad() {
    $('#exampleTable').bootstrapTable('refresh');
}

const importExcelModelFile = () => {
    layer.open({
        type: 1, // page 层类型
        area: ['500px', '300px'],
        title: '导入',
        shade: 0.6, // 遮罩透明度
        shadeClose: true, // 点击遮罩区域，关闭弹层
        maxmin: true, // 允许全屏最小化
        anim: 0, // 0-6 的动画形式，-1 不开启
        content: `
        <div class="layui-upload-drag" style="display: block;height: 100%;display: flex;flex-direction: column;align-items: center;justify-content: center;" id="ID-upload-demo-drag">
          <i class="layui-icon layui-icon-upload"></i> 
          <div>点击上传，或将文件拖拽到此处</div>
          <div class="layui-hide" id="ID-upload-demo-preview">
          </div>
        </div>
        `
    });

    layui.use(function(){
        const upload = layui.upload;
        const $ = layui.$;
        // 渲染
        upload.render({
            elem: '#ID-upload-demo-drag',
            accept: 'file', // 普通文件
            url: `/jzweb/trackDraw/importExcelTrackDraw1?cbatchId=${$('#cbatchName').val()}`, // 实际使用时改成您自己的上传接口即可。
            done: function(res){
                console.log(res)
                if(res.code * 1) {
                    layer.msg(res.msg);
                    return
                }
                layer.msg('导入成功');
                layer.closeAll()
                reLoad()
            }
        });
    });
}


/**
 * 下载导入模板
 */
const downloadExcelModelFile = () => {
    window.location.href = "/jzweb/trackDraw/exportTrackDraw1";
}

/**
 * 导出
 */
function downExcelModelFile() {
    layer.confirm('您确定要导出吗？', {
        btn1: function(index) {
            if (!isDrawing) {
                layer.msg('请先完成抽签');
                layer.close(index);
                return;
            }
            try {
                window.location.href = `/jzweb/trackDraw/exportDraw?cbatchId=${$('#cbatchName').val()}`;
                layer.close(index);
            } catch (e) {
                layer.msg('导出失败');
            }
        }
    });
}

function trackDrawCreate() {
    $.ajax({
        type: "get",
        url: `/jzweb/trackDraw/startDraw?current=${paging}&size=15&cbatchId=${$('#cbatchName').val()}`,
        async: false,
        error: function(request) {
            parent.layer.alert(request);
        },
        success: function(res) {
            if (res.code === '0') {
                console.log(res,'111')
                $('#exampleTable').bootstrapTable('load', res.data);
                let options = $('#exampleTable').bootstrapTable('getOptions');
                options.totalRows = res.data.length;
                $('#exampleTable').bootstrapTable('refreshOptions', options);
                layer.msg('抽签完毕');
            } else {
                parent.layer.alert(res.msg);
            }
        }
    });
}


/**
 * 大屏抽签
 */
const openPage =() => {
    window.open('/jzweb/trackDraw1/trackDraw3',"_blank")
}

/**
 * 开始抽签
 */
const drawBButton = () => {
    let index = layer.confirm('确定开始抽签？', {
        btn: ['确定', '取消']
    }, function() {
        let rows = $('#exampleTable').bootstrapTable('getData');
        if(!rows.length) {
            return layer.msg('请导入信息');
        }
        if (flag) {
            return layer.msg('抽签中');
        }
        flag = true;
        animateNumbers();
        layer.close(index);
    });
}

/**
 * 停止抽签
 */
const stopButton = () => {
    let index = layer.confirm('确定停止抽签？', {
        btn: ['确定', '取消']
    }, function() {
        if (flag) {
            flag = false;
            cancelAnimationFrame(animationId);
            trackDrawCreate(); // 拉取最终理论选手结果
            layer.msg('抽签已停止，结果已生成');
        } else {
            if (isDrawing) {
                layer.msg('抽签已完成');
                return;
            }
            layer.msg('请先开始抽签');
        }
        layer.close(index);
    });
}


function animateNumbers() {
    if (!flag) {
        cancelAnimationFrame(animationId);
        return;
    }

    const rows = $('#exampleTable').bootstrapTable('getData');
    if (rows.length === 0) {
        layer.msg('暂无选手信息');
        return;
    }

    const totalCount = rows.length;

    $('#exampleTable tbody tr').each(function(index) {
        const rowData = rows[index] || {};
        const pool = [rowData.name1, rowData.name2, rowData.name3, rowData.name4]
            .filter(n => n !== undefined && n !== null && String(n).trim() !== '');


        // ✅ 理论选手：从中随机挑选一个名字滚动显示
        let theoryName = '-';
        if (pool.length) {
            const randomIdx = Math.floor(Math.random() * pool.length);
            theoryName = pool[randomIdx];
        }
        $(this).find('.theory-cell').text(theoryName);

        // ✅ 序号随机滚动
        const randIdx = getRandomNumber(1, totalCount);
        $(this).find('.index-cell').text(randIdx);
    });

    animationId = requestAnimationFrame(animateNumbers);
}

// 从数组中随机取两项且不相同
function getTwoDistinctRandom(arr) {
    const i = Math.floor(Math.random() * arr.length);
    let j = Math.floor(Math.random() * (arr.length - 1));
    if (j >= i) j += 1;
    return [arr[i], arr[j]];
}

// 已有的工具函数保留
function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}